package model

import (
	"database/sql"
	"fmt"
	"gicechina/help"
	"strings"
)

type Category struct {
	Id          int    `json:"id"`
	Title       string `json:"title"`
	Pid         int    `json:"pid"`
	thumbnail   string `json:"thumbnail"`
	Content     string `json:"content"`
	Sort        int    `json:"sort"`
	Position    int    `json:"position"`
	Description string `json:"description"`
	Template    string `json:"template"`
	Status      int    `json:"status"`
	Operator    string `json:"operator"`
	UpdateTime  string `json:"update_time"`
	Url         string `json:"url"`
	Keyors        string `json:"keys"`
}

//根据条件获得栏目信息
func (c *Category) Item(pid int, title string) []Category {
	var result *sql.Rows
	var err error
	if title != "" {
		sql := "SELECT `id`,`title`,`pid`,`status`,`operator`,`update_time`,`thumbnail`,`sort`,`keyors` FROM t_category WHERE `title` LIKE '{like}' ORDER BY sort desc"
		sql = strings.Replace(sql, "{like}", "%"+title+"%", 1)
		fmt.Println("sql", sql)
		result, err = help.Db.Query(sql)
	} else {
		result, err = help.Db.Query("SELECT `id`,`title`,`pid`,`status`,`operator`,`update_time`,`thumbnail`,`sort`,`keyors` FROM t_category WHERE pid=? ORDER BY sort desc", pid)
	}
	help.CheckError(err, "根据pid获取分类信息失败")
	defer result.Close()
	var categorys []Category
	for result.Next() {
		var category Category
		err = result.Scan(&category.Id, &category.Title, &category.Pid, &category.Status, &category.Operator, &category.UpdateTime, &category.thumbnail, &category.Sort,&category.Keyors)
		help.CheckError(err, "解析分类数据失败")
		categorys = append(categorys, category)
	}
	return categorys
}

//根据id获取栏目信息
func (c *Category) GetInfoById(id int) (category Category, err error) {
	var cateInfo Category
	err = help.Db.QueryRow("SELECT `id`,`title`,`pid`,`status`,`operator`,`update_time`,`thumbnail`,`keyors`,`sort`,`content` FROM t_category WHERE id=?", id).Scan(&cateInfo.Id, &cateInfo.Title, &cateInfo.Pid, &cateInfo.Status, &cateInfo.Operator, &cateInfo.UpdateTime, &cateInfo.thumbnail,&cateInfo.Keyors,&cateInfo.Sort,&cateInfo.Content)
	if err != nil {
		help.CheckError(err, "根据栏目id获取栏目失败")
		return cateInfo, err
	}
	return cateInfo, err
}

